<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 400px;
            height: 400px;
            background-color: #f00;
            position: relative;
            margin: 50px auto;
        }
        .box span {
            width: 100px;
            height: 100px;
            background-color: #000;
            position: absolute;
        }
    </style>
</head>
<body>

    <div class="box">
        <span></span>
    </div>

    <script>

        var oBox = document.querySelector('.box') ;
        var oSpan = document.querySelector('span') ;

        // oSpan.onmousedown = function(e) {

        //     var gapX = e.x ;
        //     var gapY = e.y ;
        //     document.onmousemove = function(e) {
        //         var x = e.x - gapX ;
        //         var y = e.y - gapY ;

        //         oSpan.style.cssText = `left:${x}px;top:${y}px;`
        //     }
        // }


        oSpan.onmousedown = function(e) {

            // 鼠标按下的时候，拿到鼠标在盒子中的位置
            var gapX = e.offsetX ;
            var gapY = e.offsetY ;
            document.onmousemove = function(e) {
                var x = e.x - gapX - oBox.offsetLeft ;
                var y = e.y - gapY - oBox.offsetTop;

                oSpan.style.cssText = `left:${x}px;top:${y}px;`
            }
        }

        oSpan.onmouseup = function() {
            document.onmousemove = null ;
        }


        
            

    </script>
    
</body>
</html>